<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\Binding;
use app\common\model\Staff;
use app\common\model\StaffUpdateLog;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 客户管理
 *
 * @icon fa fa-circle-o
 */
class Connection extends Backend
{

    /**
     * Connection模型对象
     * @var \app\common\model\Connection
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Connection;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("strikeDataList", $this->model->getStrikeDataList());
        $this->view->assign("collisionDataList", $this->model->getCollisionDataList());
        $this->view->assign("typeDataList", $this->model->getTypeDataList());
    }





    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $type_data=$this->request->param("type_data")?$this->request->param("type_data"):0;
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = $this->request->request("filter");
            $filter=json_decode($filter,true);
            $op = json_decode($this->request->request("op"),true);
            $key=1;
            if(!array_key_exists("type_data",$filter)){
                $filter["connection.type_data"]="0";
                $op["connection.type_data"]="=";
                $this->request->get(["filter"=>json_encode($filter),'op'=>json_encode($op)]);
                $key=0;
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['staff'=>function($query){
                    $query->withField('id,name,mobile');
                },'bindStaff'=>function($query){
                    $query->withField('id,name,mobile');
                },'canal'=>function($query){
                    $query->withField('id,name');
                }])
                ->field("connection.*,ibec.name 'ibec.name',staff_ibec.name 'staff_ibec.name'")
                ->join("ibec","ibec.id=bindStaff.ibec_id","left")
                ->join("ibec staff_ibec","staff_ibec.id=staff.ibec_id","left")
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as &$row){
                $log=StaffUpdateLog::where(["connection_id"=>$row["id"]])->find();
                $row["bind_status"]=empty($log)?false:true;
            }
            $result = array("total" => $list->total(), "rows" => $list->items(),'key'=>$key);

            return json($result);
        }
        $this->assign("type_data",$type_data);
        return $this->view->fetch();
    }
    /**
     * 详情
     */
    public function see($id){
        $row = $this->model
            ->with(['staff'=>function($query){
                $query->withField('id,name,mobile,ibec_id');
            },'bindStaff'=>function($query){
                $query->withField('id,name,mobile,ibec_id');
            },'canal'=>function($query){
                $query->withField('id,name,mobile');
            } ])
            ->where(["connection.id"=>$id])
            ->field("connection.*,ibec.name 'ibec.name',staff_ibec.name 'staff_ibec.name'")
            ->join("ibec ibec","ibec.id=bindStaff.ibec_id","left")
            ->join("ibec staff_ibec","staff_ibec.id=staff.ibec_id","left")
            ->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->assign("row",$row);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        //if($row["bind_staff_id"]==$params["bind_staff_id"]) $this->error("没有任何改变");
        Db::startTrans();
        try {
            /*if(array_key_exists('avatar',$params)){
                if(!empty($params["avatar"]) && !strstr($params["avatar"],"http")) $params["avatar"]=cdnurl($params["avatar"],true);
            }
            $params["moniker"]=$params["surname"].$params["name"];
            $params["phone_see"]=substr($params["phone"],0,3)."****".substr($params["phone"],-4,4);*/
            $staff=\app\common\model\Staff::get($row["bind_staff_id"]);
            $bind_staff=\app\common\model\Staff::get($params["bind_staff_id"]);
            $time=time();
            if($row["bind_staff_id"]!=$params["bind_staff_id"]){
                $data=[
                    "admin_id"=>$this->auth->id,
                    "connection_id"=>$row["id"],
                    "staff_id"=>$staff["id"],
                    "after_staff_id"=>$bind_staff["id"],
                    "content"=>"修改前经纪人“".$staff["name"]."”,修改后经纪人“".$bind_staff["name"]."”",
                    "createtime"=>$time
                ];

                $list=\app\common\model\Connection::where(["surname"=>$row["surname"],"phone"=>$row["phone"]])
                    ->where("status !='4' and status !='3'")->select();
                if(!empty($list)){
                    $update=[];
                    foreach ($list as $k=>$v){
                        $update[$k]=[
                            "bind_time"=>$time,
                            "id"=>$v["id"],
                            "bind_staff_id"=>$params["bind_staff_id"],
                        ];
                    }
                }
                if(!empty($update)){
                    $this->model->saveAll($update);
                }
                StaffUpdateLog::create($data);
                //绑定表新增记录
                $loseTime=\think\Config::get('site.loseTime');
                $lapse_time=strtotime("+".$loseTime." days",strtotime(date("Y-m-d",time())));
                Binding::create([
                    "connection_id"=>$row["id"],
                    "staff_id"=>$this->auth->id,
                    "lapse_time"=>$lapse_time,
                    "createtime"=>time(),
                    "dynatown_id"=>$this->auth->id,
                    "type_data"=>"1",
                ]);
            }
            $update_data=[];
            if(array_key_exists('bind_staff_id',$params)){
                $update_data=[
                    "bind_staff_id"=>$params["bind_staff_id"],
                    "bind_time"=>$time,
                ];
            }
            if(array_key_exists('canal_id',$params)){
                $update_data["canal_id"]=$params["canal_id"];
            }
            if(!empty($update_data)){
                $result = $row->allowField(true)->save($update_data);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 修改客户为已成交
     * */
    public function operation(){
        if (!$this->request->param("ids")) $this->error('id为空');
        $param=$this->request->param();
        $row = $this->model->get($param["ids"]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $param["strike_time"]=time();
        $param["strike_data"]='1';
        $result = $row->allowField(true)->save($param);
        if ($result !== false) {
            $this->success();
        } else {
            $this->error(__('No rows were updated'));
        }
    }

    /**
     * 绑定经纪人修改记录
     * */
    public function updateLog($id){
        $row = StaffUpdateLog::
        with(["admin"=>function($query){
            $query->withField('id,nickname');
        }])
            ->where(["connection_id"=>$id])->order("createtime","desc")->select();
        /*if (!$row) {
            $this->error(__('No Results were found'));
        }*/
        $this->assign("row",$row);
        return $this->view->fetch();
    }
    /**
     * 填写备注
     * */
    public function remark($id=0){
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {

            $this->assign("row",$row);
            return $this->view->fetch();
        }
        $row->remark=$this->request->param("remark");
        $row->save();
        $this->success();
    }
}
